function rvalue = glm_WriteAnalyzeVols(hfile, cons)
% GLM::WriteAnalyzeVols  - write Analyze images from a GLM file
%
% FORMAT:       [success = ] glm.WriteAnalyzeVols(cons)
%
% Input fields:
%
%       cons        1xC struct with settings
%        .c         Px1 contrast vector
%        .pattern   filename pattern with tokens
%                   $s for subject ID
%                   $c contrast name with _ and GT replacements
%                   if empty, default: '$s_$c.img'
%
% Output fields:
%
%       success     true if successful

% Version:  v0.7g
% Build:    9101519
% Date:     Oct-15 2009, 7:22 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'glm') || ...
   ~isstruct(cons) || ...
    isempty(cons) || ...
   ~isfield(cons, 'c')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
sc = bvqxfile_getscont(hfile.L);
bc = sc.C;
if isempty(bc.Map) || ...
    mapno > numel(bc.Map)
    error( ...
        'BVQXfile:BadArgument', ...
        'Empty VMP or map number too high.' ...
    );
end
bcm = bc.Map(mapno);

% default rvalue
rvalue = false;

% filename
filename = filename(:)';
filename = [filename(1:end-3) 'img'];
hdrfname = [filename(1:end-3) 'hdr'];
matfname = [filename(1:end-3) 'mat'];

% dimension and datatype
xyzres = bc.Resolution;
vmpdat = single(permute(bcm.VMPData(end:-1:1, end:-1:1, end:-1:1), [3, 1, 2]));
vmpdsc = bcm.Name;
if numel(vmpdsc) > 80
    vmpdsc = [vmpdsc(1:77) '...'];
end
isiz = size(vmpdat);
offx = bc.ZEnd - 128;
offy = bc.XEnd - 128;
offz = bc.YEnd - 128;
orgx = 1 + round(offx / xyzres);
orgy = 1 + round(offy / xyzres);
orgz = 1 + round(offz / xyzres);

% build mat
tmat = xyzres .* eye(4);
tmat(end) = 1;
tmat(1:3, 4) = -[offx; offy; offz];

% try volume creation
hdrc = cell(1, 1);
try
    hdr = BVQXfile('new:hdr');
    hdrc{1} = hdr;
    hdrbc = bvqxfile_getcont(hdr.L);
catch
    clearbvqxobjects(hdrc);
    error( ...
        'BVQXfile:InternalError', ...
        'Error creating Analyze header object: %s.', ...
        lasterr ...
    );
end

% set dims and data
hdrbc.ImgDim.Dim(1:4) = [3, isiz];
hdrbc.ImgDim.PixSpacing(2:4) = [xyzres, xyzres, xyzres];
hdrbc.ImgDim.DataType = 16;
hdrbc.ImgDim.BitsPerPixel = 32;
hdrbc.ImgDim.CalMaxDisplay = 32767;
hdrbc.ImgDim.CalMinDisplay = -32768;
hdrbc.DataHist.Description = vmpdsc;
hdrbc.DataHist.OriginSPM = [orgx, orgy, orgz, 0, 0];
hdrbc.VoxelData = vmpdat;
bvqxfile_setcont(hdr.L, hdrbc);

% save hdr/img
try
    aft_SaveAs(hdr, hdrfname);
    rvalue = hdr_SaveVoxelData(hdr);
catch
    warning( ...
        'BVQXfile:InternalError', ...
        'Error writing Analyze header/image %s.', ...
        hdrfname ...
    );
    return;
end
if ~rvalue
    return;
end

% save mat
eval('M=tmat;mat=tmat;save(matfname,''M'',''mat'',''-v6'');', '')
if exist(matfname, 'file') ~= 2
    rvalue = false;
end
